package com.tfswx.jcyw.print;

import com.tfswx.jcyw.print.config.Ggpz;
import com.tfswx.jcyw.print.exception.AppException;
import com.tfswx.jcyw.print.log.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Properties;

/**
 * @author ricky
 * @date 2021/8/3
 */
@Slf4j
@SpringBootApplication
public class Client extends Application {
    @SneakyThrows
    public static void main(String[] args) {
        FileUtils.cleanDirectory(Ggpz.AZB_DIR);
        launch(args);
    }

    private static String getVersion() {
        ClassPathResource classPathResource = new ClassPathResource("bbinfo.properties");
        try (InputStream inStream = classPathResource.getInputStream();
             ByteArrayOutputStream bos = new ByteArrayOutputStream(inStream.available())) {
            byte[] buff = new byte[2048];
            int len;
            while ((len = inStream.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
            byte[] bytes = bos.toByteArray();
            bos.flush();
            Properties p = new Properties();
            p.load(new ByteArrayInputStream(bytes));
            String version = p.getProperty("bbinfo.version");
            return version;
        } catch (IOException e) {
            throw new AppException("读取版本号失败", e);
        }
    }

    private Parent rootNode;
    private static ServerSocket server;
    private static Stage primaryStage;

    private static Image winIcon;
    private static String winTitle;

    private static String ver;

    @Override
    public void init() throws Exception {
        winIcon = new Image(getClass().getClassLoader().getResource("image/icon.png").toString());
        ver = getVersion();
        winTitle = "批量打印 v" + ver;

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/sample.fxml"));
        rootNode = loader.load();
        Sample controller = loader.getController();
        Parameters parameters = getParameters();
        List<String> raw = parameters.getRaw();
        try {
            log.info("开始启动Socket服务");
            server = new ServerSocket(25654);
            for (String filePath : raw) {
                controller.addFile(new File(filePath));
            }
            log.info("启动Socket服务成功");
        } catch (BindException e) {
//            log.info("端口被占用");
            // 端口被占用。证明已有服务启动


            //创建一个Socket，跟服务器的8080端口链接
            log.info("正在尝试与服务器建立连接");
            try (Socket socket = new Socket("localhost", 25654);
                 PrintWriter pw = new PrintWriter(socket.getOutputStream())) {
                //使用PrintWriter和BufferedReader进行读写数据
                //发送数据
                log.info("正在向服务器发送文件路径");
                for (String filePath : raw) {
                    pw.println(filePath);
                    pw.flush();
                }
            }

            System.exit(1);
        }

        new Thread(() -> {
            while (!server.isClosed()) {
                try {
                    Socket socket = server.accept();
                    BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
                    String line = is.readLine();
                    log.info(line);
                    Platform.runLater(() -> {
                        log.info(line);
                        controller.addFile(new File(line));
                    });
                } catch (Exception e) {
                    if (!server.isClosed()) {
                        log.error("Socket服务异常", e);
                    }
                }
            }
        }).start();
    }

    public static void close() {
        if (primaryStage != null) {
            primaryStage.close();
        }
        Logger.getDisruptor().shutdown();
        if (server != null) {
            try {
                server.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void start(Stage primaryStage) {
        setPrimaryStage(primaryStage);
        primaryStage.initStyle(StageStyle.TRANSPARENT);
        primaryStage.setTitle(winTitle);
        primaryStage.setResizable(false);

        primaryStage.getIcons().add(winIcon);
        Scene scene = new Scene(rootNode, 780, 723);
        scene.getStylesheets().add("my.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private static void setPrimaryStage(Stage primaryStage) {
        Client.primaryStage = primaryStage;
    }

    public static Stage getPrimaryStage() {
        return primaryStage;
    }

    public static Image getWinIcon() {
        return winIcon;
    }

    public static String getWinTitle() {
        return winTitle;
    }

    public static String getVer() {
        return ver;
    }
}
